import { catchManager } from './catchManager';
import  Rx  from 'rxjs';
import isGeneratorFunctionName from 'is-generator-function-name';

export function Cacheable(value,keyReducer: (...args)=>any = null) {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        let method = descriptor.value;
        if(isGeneratorFunctionName(method)){
            descriptor.value = async function (...args) {
                try {
                    let self = this;
                    catchManager.addOrReplaceCache(value+keyReducer(...args),await method.apply(self, args)) 
                    const result = catchManager.getValue(value+keyReducer(...args))
                    return result;
                } catch (error) {
                    throw error;
                }
            }
        } else {
            descriptor.value = function (...args) {
                try {
                    let self = this;
                    catchManager.addOrReplaceCache(value+keyReducer(...args),method.apply(self, args)) 
                    const result = catchManager.getValue(value+keyReducer(...args))
                    return result;
                } catch (error) {
                    throw error;
                }
            }            
        }
    }
}

export function CachePut(value,keyReducer: (...args)=>any = null) {
    return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        let method = descriptor.value;
        if(isGeneratorFunctionName(method)){
            descriptor.value = async function (...args) {
                try {
                    let self = this;
                    catchManager.addOrReplaceCache(value+keyReducer(...args),await method.apply(self, args)) 
                    const result = catchManager.getValue(value+keyReducer(...args))
                    return result;
                } catch (error) {
                    throw error;
                }
            }
        } else {
            descriptor.value = function (...args) {
                try {
                    let self = this;
                    catchManager.addOrReplaceCache(value+keyReducer(...args), method.apply(self, args)) 
                    const result = catchManager.getValue(value+keyReducer(...args))
                    return result;
                } catch (error) {
                    throw error;
                }
            }            
        }
    }
}

export function CacheEvict(value="accountCache",key="#"){

}
